// Package api
// @Author: zhangdi
// @File: menu
// @Version: 1.0.0
// @Date: 2023/8/28 10:33
package sysctrl

import (
	"server/application/db/system/dbdto"
	dbsvc2 "server/application/db/system/dbsvc"
	"server/application/db/system/repository"
	"server/pkg/ginp"
	"server/pkg/where"
)

// GetMenuTreeList 获取树形性菜单
func GetMenuTreeList(ctx *ginp.ContextPro) {
	list, err := dbsvc2.SysMenuFindList(where.Format(), nil)
	if err != nil {
		return
	}
	treeList := dbsvc2.BuildMenuTree(list, 0)
	soreTreeList := dbsvc2.SortMenuTree(treeList)
	ctx.OkJsonData(soreTreeList)
}

// GetMenuTreePermission 获取菜单权限列表
func GetMenuTreePermission(ctx *ginp.ContextPro) {
	list, err := dbsvc2.SysMenuFindList(where.Format(), nil)
	if err != nil {
		return
	}
	treeList := dbsvc2.BuildMenuTreePermission(list, 0)
	soreTreeList := dbsvc2.SortTreePermissionBySort(treeList)
	//叶子结点加上权限
	dbsvc2.MenuTreeAddChildrenToLeafNodes(soreTreeList)
	ctx.OkJsonData(soreTreeList)
}

// GetMenuSelectTreeList 构造树形菜单下拉框
func GetMenuSelectTreeList(ctx *ginp.ContextPro) {
	list, err := dbsvc2.SysMenuFindList(where.Format(), nil)
	if err != nil {
		return
	}
	treeList := dbsvc2.BuildAdMenuTreeSelect(list, 0)
	soreTreeSelectList := dbsvc2.SortTreeSelectBySort(treeList) //排序
	ctx.OkJsonData(soreTreeSelectList)
}

func MenuCreate(ctx *ginp.ContextPro) {
	var params *dbdto.SysMenuCreate
	if err := ctx.ShouldBindJSON(&params); err != nil {
		ctx.ErrJson("请求参数有误" + err.Error())
		return
	}
	info, err := dbsvc2.SysMenuCreate(params)
	if err != nil {
		ctx.ErrJson("创建失败" + err.Error())
		return
	}
	ctx.OkJsonData(info)
}

func MenuUpdate(ctx *ginp.ContextPro) {
	var params *dbdto.SysMenuUpdate
	if err := ctx.ShouldBindJSON(&params); err != nil {
		ctx.ErrJson("请求参数有误" + err.Error())
		return
	}

	wheres := where.Format(where.OptEqual("id", params.ID))
	err := dbsvc2.SysMenuUpdate(wheres, params, repository.UpdateColumnsAll)
	if err != nil {
		ctx.ErrJson("修改失败" + err.Error())
		return
	}
	ctx.OkJson()
}

func MenuDelete(ctx *ginp.ContextPro) {
	var params *dbdto.SysMenuDelete
	if err := ctx.ShouldBindJSON(&params); err != nil {
		ctx.ErrJson("请求参数有误" + err.Error())
		return
	}

	err := dbsvc2.SysMenuDelete(where.FormatOne("id", "IN", params.ID))
	if err != nil {
		ctx.ErrJson("删除失败" + err.Error())
		return
	}
	ctx.OkJson()
	return
}

// GetMenuNames 获取名称列表
func GetMenuNames(ctx *ginp.ContextPro) {
	names := dbsvc2.SysMenuGetNames()
	ctx.OkJsonData(names)
}
